<template>
    <a-modal
        :keyboard="false"
        :maskClosable="false"
        :title="`【${modelRef.chargePerson}】${titleList[modelRef.detailType]}`"
        :open="visible"
        :width="1200"
        :confirmLoading="loading"
        centered
        @cancel="handleCancel"
    >
        <a-table
            :row-class-name="stripe"
            :size="state.tableSize"
            :loading="state.loading"
            :columns="dynamicColumns"
            :data-source="state.dataSource"
            :pagination="{
                'show-size-changer': true,
                current: state.current,
                pageSize: state.pageSize,
                total: state.total,
                showTotal: total => `共 ${total} 条`,
            }"
            ref="tableRef"
            :scroll="{ x: 1150, y: 300 }"
            @change="handleTableChange"
            border
            @resizeColumn="handleResizeColumn"
        >
            <template #bodyCell="{ record, column }">
                <template v-if="column.dataIndex === 'orderNum'">
                    <div class="order-no">
                        {{ record.orderNum }}
                        <a-tag v-if="record.orderType === 1" color="#cd201f">投诉</a-tag>
                    </div>
                </template>
                <template v-if="column.dataIndex === 'orderState'">
                    {{ statusMap[record.orderState] }}
                </template>
                <template v-else-if="column.dataIndex === 'orderProperty'">
                    {{ propertyMap[record.orderProperty] }}
                </template>
                <template v-else-if="column.dataIndex === 'orderSource'">
                    {{ formatSource(record.orderSource) }}
                </template>
                <template v-else-if="column.dataIndex === 'contact'">
                    {{ [record.propertyOwner, record.propertyPhone].filter(Boolean).join('/') }}
                </template>
                <!-- <template v-else-if="column.dataIndex === 'action'">
                    <a-button>审核</a-button>
                </template> -->
            </template>
        </a-table>
    </a-modal>
</template>

<script lang="ts">
import type { PropType } from 'vue';
import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
import { cloneDeep } from 'lodash-es';
import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
import { getOrderStatisticsProjectPage } from '@/api/order/statistics';
import type { Pagination, TableColumn } from '@/typing';
import { useFetchData } from '@/utils/hooks/useFetchData';
import { statusMap, propertyMap, typeMap } from '@/views/order/mine/mine-list/common';
import { isUndefined, isNull, isEmpty } from 'xe-utils';
import { dictDataListByDictType } from '@/api/user/dict';
import dayjs from 'dayjs';

const titleList = ref(['', '被抽检总数', '被抽检不合格数', '未首条跟进数', '未完成工单数', '工单评价数', '工单不满意数']);

const baseColumns: TableColumn[] = [
    {
        title: '工单编号',
        dataIndex: 'orderNum',
        width: 180,
        resizable: true,
        ellipsis: true,
        fixed: 'left',
    },
    {
        title: '项目名称',
        dataIndex: 'projectName',
        width: 120,
        resizable: true,
        ellipsis: true,
    },
    {
        title: '工单详情',
        dataIndex: 'content',
        width: 120,
        resizable: true,
        ellipsis: true,
    },
    {
        title: '工单来源',
        dataIndex: 'orderSource',
        width: 100,
        resizable: true,
        ellipsis: true,
    },
    {
        title: '工单类型',
        dataIndex: 'orderType',
        width: 90,
        resizable: true,
        ellipsis: true,
        customRender: ({ text }) => typeMap[text],
    },
    {
        title: '工单分类',
        dataIndex: 'orderClassifyName',
        width: 90,
        resizable: true,
        ellipsis: true,
    },
    {
        title: '客户房号',
        dataIndex: 'propertyRoom',
        width: 150,
        resizable: true,
        ellipsis: true,
    },
    {
        title: '工单状态',
        dataIndex: 'orderState',
        width: 90,
        resizable: true,
        ellipsis: true,
    },
    {
        title: '当前负责人',
        dataIndex: 'orderChargePerson',
        width: 110,
        resizable: true,
        ellipsis: true,
    },
    {
        title: '提报人',
        dataIndex: 'creatorName',
        width: 160,
        resizable: true,
        ellipsis: true,
    },
    {
        title: '提报时间',
        dataIndex: 'createTime',
        ellipsis: true,
        width: 120,
        resizable: true,
    },
    {
        title: '联系人',
        dataIndex: 'contactPerson',
        width: 90,
        resizable: true,
    },
    {
        title: '联系电话',
        dataIndex: 'contactPersonPhone',
        width: 130,
        resizable: true,
    },
];

export default defineComponent({
    props: {
        visible: {
            type: Boolean,
            required: true,
        },
        model: {
            type: Object as PropType<any>,
            default: () => [],
        },
    },
    emits: ['cancel', 'confirm', 'success'],
    setup(props, { emit }) {
        const loading = ref(false);

        const { state: columnState, dynamicColumns, dynamicColumnItems } = useTableDynamicColumns(baseColumns, { needRowIndex: false });
        const modelRef = reactive<any>({});

        // 记录初始值
        const initValues = reactive({});

        const queryParams = reactive<any>({});

        const fetchDataContext = reactive<any>({
            current: 1,
            pageSize: 10,
            tableSize: 'middle', // 'default' | 'middle' | 'small'
            stripe: false,
            executeImmediately: false,
            requestParams: { ...queryParams },
        });

        const { stripe, context: state, reload } = useFetchData(getOrderStatisticsProjectPage, fetchDataContext);

        const dictData = reactive({
            xmytData: [],
        });
        watch(
            () => props.visible,
            () => {
                Object.assign(initValues, cloneDeep(props.model));
            },
        );
        watchEffect(() => {
            if (props.visible) {
                Promise.all([
                    dictDataListByDictType({
                        dictType: 'order_ascription',
                    }),
                ]).then(res => {
                    const [xmytData] = res;
                    dictData.xmytData = xmytData.data;
                });
                if (props.model.projectCode) {
                    Object.assign(modelRef, cloneDeep(props.model));
                    Object.assign(queryParams, {
                        projectCodes: modelRef.queryParams.projectCode,
                        detailType: modelRef.detailType,
                        chargePersonId: modelRef.chargePersonId,
                        statisticsType: modelRef.dimension,
                        ...modelRef.queryParams,
                    });
                    delete queryParams.projectCode;
                    const { orderTime = [], ...params } = queryParams;

                    if (!isEmpty(orderTime) && orderTime.length === 2) {
                        params.orderTimeStart = dayjs(orderTime[0]).format('YYYY-MM-DD') + ' 00:00:00';
                        params.orderTimeEnd = dayjs(orderTime[1]).format('YYYY-MM-DD') + ' 23:59:59';
                    }
                    fetchDataContext.requestParams = { ...params };

                    fetchDataContext.executeImmediately = true;
                }
            }
        });

        const formatSource = (source: string) => {
            if (isUndefined(source) || isEmpty(dictData.xmytData)) return '';
            return dictData.xmytData.find(item => item.value === source)?.label || '';
        };

        const handleTableChange = ({ current, pageSize }: Pagination) => {
            fetchDataContext.current = current;
            fetchDataContext.pageSize = pageSize;
        };

        const handleCancel = () => {
            Object.keys(queryParams).forEach(key => {
                delete queryParams[key];
            });
            Object.keys(modelRef).forEach(key => {
                delete modelRef[key];
            });
            emit('cancel');
        };

        const handleResizeColumn = (w, col) => {
            col.width = w;
        };

        return {
            handleResizeColumn,
            titleList,
            handleTableChange,
            formatSource,
            loading,
            stripe,
            state,
            reload,
            columnState,
            dynamicColumns,
            dynamicColumnItems,

            modelRef,

            initValues,

            handleCancel,

            statusMap,
            propertyMap,
            typeMap,
        };
    },
});
</script>

<style lang="less" scoped></style>
